package py.com.alfa.escriba.gui.rest.interceptors;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.support.HttpRequestWrapper;

import py.com.alfa.escriba.gui.config.ConfigLocator;
import py.com.alfa.escriba.gui.config.EscribaGUIApplicationContextProvider;
import py.com.alfa.escriba.gui.services.Services;
import py.com.alfa.escriba.gui.session.SystemInfo;
import py.com.alfa.escriba.gui.utils.ObjectUtils;

public class RequestInterceptor implements ClientHttpRequestInterceptor {

	private Logger log = LoggerFactory.getLogger(getClass());

	public RequestInterceptor() {
	}

	@Override
	public ClientHttpResponse intercept(HttpRequest request, byte[] body,
			ClientHttpRequestExecution execution) throws IOException {
		log.info("Intercepting Request");
		ApplicationContext ctx = EscribaGUIApplicationContextProvider
				.getContext();
		HttpRequestWrapper requestWrapper = new HttpRequestWrapper(request);
		SystemInfo systemInfo = (SystemInfo) ctx.getBean(Services.SYSTEM_INFO);
		ConfigLocator config = (ConfigLocator) ctx
				.getBean(Services.CONFIG_LOCATOR);
		requestWrapper.getHeaders().add("user-principal",
				systemInfo.getNombreUsuario());
		requestWrapper.getHeaders().add("app-name",
				config.getConfig().getAppName());
		requestWrapper.getHeaders().add("app-page", request.getURI().getPath());

		if (ObjectUtils.isNotEmpty(systemInfo.getIdUser()))
			requestWrapper.getHeaders().add("id-user-principal",
					systemInfo.getIdUser().toString());
		
		if (ObjectUtils.isNotEmpty(systemInfo.getIdEscribano()))
			requestWrapper.getHeaders().add("id-escribano",
					systemInfo.getIdEscribano().toString());

		log.info("Headers: {}", requestWrapper.getHeaders());

		return execution.execute(requestWrapper, body);
	}

}
